<!-- 作者:高翔宇 时间:2024/5/28 周二 20:02 -->
<script setup lang="ts">
import {Picture as IconPicture} from "@element-plus/icons-vue";
import {UploadProps} from "element-plus";
import {onMounted, reactive, ref} from 'vue'
import {useUserStore} from "@/store";

const userStore = useUserStore()

// 统一管理加载状态
const loading = reactive({
  updateUsername: false,
  updateIntroduction: false
})
defineProps({
  show: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(["update:show"])

onMounted(() => {
  formModel.username = userStore.userInfo.username
  formModel.introduction = userStore.userInfo.introduction
})

const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确认关闭?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    emit('update:show', false)
    done()
  }).catch(() => {
    // catch error
  })
}

const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9_-]{4,16}$/, message: '用户名必须是4-16位字母、数字、\\或-组成', trigger: 'blur'}
  ],
  introduction: [
    {required: true, message: '请输入签名', trigger: 'blur'},
    {max: 20, message: '签名不能超过20个字符', trigger: 'blur'}
  ]
}
/**
 * 此函数配合el-upload的action属性，action是一个url
 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  console.log('uploadFile', uploadFile)
  if (response.code !== 200) {
    ElMessage.error('上传失败')
    return
  } else {
    ElMessage.success('上传成功')
    userStore.getUserInfo()
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile)
}

const updateUserInfoRef = ref()

const formModel = reactive({
  username: '',
  introduction: '',
})

function getUserInfo() {
  userStore.getUserInfo().then(() => {
    formModel.username = userStore.userInfo.username
    formModel.introduction = userStore.userInfo.introduction
  })
}

/**
 * 更新用户名
 */
function updateUsername() {
  updateUserInfoRef.value.validateField('username').then(() => {
    loading.updateUsername = true
    userStore.updateUserName(formModel.username).then(() => {
      ElMessage.success('修改成功')
    }).catch(() => {
      ElMessage.error('修改失败')
    }).finally(() => {
      loading.updateUsername = false
      getUserInfo()
    })
  })
}

/**
 * 更新签名
 */
function updateIntroduction() {
  updateUserInfoRef.value.validateField('introduction').then(() => {
    loading.updateIntroduction = true
    userStore.updateIntroduction(formModel.introduction).then(() => {
      ElMessage.success('修改成功')
    }).catch(() => {
      ElMessage.error('修改失败')
    }).finally(() => {
      loading.updateIntroduction = false
      getUserInfo()
    })
  })
}
</script>

<template>
  <el-drawer id="updateUserInfoDrawer" :model-value="show" :direction="'rtl'" size="40%" :before-close="handleClose">
    <template #header>
      <h4>修改信息</h4>
    </template>
    <template #default>
      <el-form ref="updateUserInfoRef" :model="formModel" label-width="80px" :rules="rules">
        <el-form-item label="上传头像">
          <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :action="'http://localhost:5603/api/user/avatar'"
              :headers="{'token': userStore.userState.token}"
              name="avatar"
          >
            <el-image :src="userStore.userInfo?.avatar" class="avatar" alt="666">
              <template #error>
                <el-icon size="20px" style="width: 178px; height: 178px">
                  <icon-picture/>
                </el-icon>
              </template>
            </el-image>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-col :span="16">
            <el-input aria-label="用户名" v-model="formModel.username" style="width: 80%;" show-word-limit
                      placeholder="请输入用户名"/>
          </el-col>
          <el-col :span="8" class="align-right">
            <el-button type="primary" @click="updateUsername()" :loading="loading.updateUsername">提交</el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="个性签名" prop="introduction">
          <el-col :span="16">
            <el-input v-model="formModel.introduction" style="width: 80%;" rows="5" autosize maxlength="20"
                      show-word-limit type="textarea"
                      resize="none" max="20" placeholder="请输入签名"/>
          </el-col>
          <el-col :span="8" class="align-right">
            <el-button type="primary" @click="updateIntroduction()" :loading="loading.updateIntroduction">提交
            </el-button>
          </el-col>
        </el-form-item>
      </el-form>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">
#updateUserInfoDrawer {
  h1 {
    font-size: 20px;
    margin-bottom: 20px;
  }

  .avatar-uploader {
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}

</style>
